<template>
  <ex-dialog
    width="1200px"
    class="ex-diolog"
    :title="title"
    :visible="visible"
    :close-on-click-modal="false"
    @closeDialog="handleClose"
  >
    <div class="main" v-loading="loading">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm" :disabled="disabled" >
        <div class="title">活动基本信息</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动名称：" prop="bpaData.name">
              <el-input
                maxlength="50"
                placeholder="请填写活动名称"
                v-model="ruleForm.bpaData.name">
              </el-input>
            </el-form-item> 
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="弹窗图片:" prop="bpaData.img"  ref="imgRef">
              <ImageUpload :limit="1" @successImg="successImg" :value="ruleForm.bpaData.img" @input="handleRemove"></ImageUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动时间：" prop="date"> 
              <el-date-picker
                v-model="ruleForm.date"
                @change="getTime"
                type="datetimerange"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" v-if="pathType == 'add'">
            <el-form-item label="活动名额：" prop="bpaData.stock">
              <el-input placeholder="请输入活动名额" v-model="ruleForm.bpaData.stock">
                <template slot="append">份</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="pathType == 'edit'">
            <el-form-item label="添加活动名额：">
              <el-input placeholder="请输入添加活动名额" v-model="ruleForm.bpaData.stock">
                <template slot="append">份</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4" v-if="pathType == 'edit'">
            <div class="stockNum">活动剩余名额: {{residueStock}}</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="参与条件：" prop="bpaData.joinCondition">
              <el-radio-group v-model="ruleForm.bpaData.joinCondition">
                <el-radio :label="'1'">不限</el-radio>
                <el-radio :label="'2'">未消费过的用户</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">领取奖励设置</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="积分类型：" prop="bpaData.rewardType">
              <el-select v-model="ruleForm.bpaData.rewardType" placeholder="请选择积分类型" size="small" :disabled="pathType == 'edit'">
                <el-option v-for="item in integralTypeList" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="领取数额：" prop="bpaData.rewardNum">
              <el-input placeholder="请输入领取数额" v-model="ruleForm.bpaData.rewardNum">
                <template slot="append" v-if="ruleForm.bpaData.rewardType == 1">CoCo</template>
                <template slot="append" v-if="ruleForm.bpaData.rewardType == 2">椰分</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">产品抵扣设置</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="抵用限制：" prop="bpasData.useNum">
              <el-input placeholder="请输入次数" v-model="ruleForm.bpasData.useNum">
                <template slot="prepend">每位用户只能抵扣</template>
                <template slot="append">次</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="赚卡：" prop="bpaData.cardId">
              <el-select v-model="ruleForm.bpaData.cardId" multiple placeholder="请选择赚卡" filterable  size="small" @change="changecardId($event)" @remove-tag="removeTag($event)" value-key="equityCardId">
                <el-option v-for="item in cardList" :key="item.equityCardId" :label="item.cardName" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 20px">
          <el-col :span="24">
            <el-table :data="ruleForm.bpaccDataList" border >
              <el-table-column label="序号"  type="index" width="50" />
              <el-table-column label="发行店铺" align="center" prop="shopName" :show-overflow-tooltip="true" />
              <el-table-column label="卡名称" align="center" prop="cardName" :show-overflow-tooltip="true" />
              <el-table-column label="售价" align="center" prop="price" :show-overflow-tooltip="true" />
              <el-table-column label="库存总量" align="center" prop="issueTotal" :show-overflow-tooltip="true" />
              <el-table-column label="剩余库存" align="center" prop="usable" :show-overflow-tooltip="true" />
              <el-table-column label="销售状态" align="center" prop="sellStatusDict" :show-overflow-tooltip="true" />
              <el-table-column label="最高可用椰分抵扣" align="center" prop="costPrice" width="200">
                <template slot-scope="scope">
                  <el-form-item label="" label-width="0" :prop="'bpaccDataList.' + scope.$index + '.deductionNum'" :rules="rules.deductionNum">
                    <el-input  placeholder="请输入最高可用椰分抵扣" v-model="scope.row.deductionNum" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  width="100">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="shopVOListdetele(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="button_box">
      <el-button
        type="primary"
        :loading="AgreeLoading"
        @click="submitForm('ruleForm',2)"
      >保存提交</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </ex-dialog>
</template>
<script>
import Loading from "@/components/Loading/index";
// api
import {
  addPopActivity,
  editPopActivity,
  cardSelect,
  popActivityDetail,
} from "@/api/consumeMiningManagement/popupActivity";
import '@wangeditor/editor/dist/css/style.css'
import {
  Editor,
  Toolbar
} from "@wangeditor/editor-for-vue";
import WangEditor from '@/components/WangEditor'
export default {
  components: {
    Loading,
    WangEditor,
    Editor,
    Toolbar
  },
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  data() {
    var checkUseNum = (rule, value, callback) => {
        //总库存限制数量校验
        let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
      if (!value ) {
        return callback(new Error("请输入次数"));
      } else if (regNumber.test(value) == false) {
        return callback(new Error("请输入大于0正整数"));
      } else {
        return callback();
      }
    };
    
    var checkStock = (rule, value, callback) => {
      //总库存限制数量校验
      let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
      if (!value && value != 0 ) {
        return callback(new Error("请输入活动名额"));
      } else if (regNumber.test(value) == false) {
        return callback(new Error("请输入大于0正整数"));
      } else {
        return callback();
      }
    };
    var checkRewardNum = (rule, value, callback) => {
      var num = rule.field.substr(32,1)
      console.log('num',num)
      let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
      if (!value) {
        return callback(new Error("请输入领取数额"));
      } else if (regNumber.test(value) == false) {
        return callback(new Error("请填写大于0且最多保留两位小数的数值"));
      } else {
        return callback();
      }
      
    };
    var checkDeductionNum = (rule, value, callback) => {
      let arr = rule.field.split('.')
      var num = arr[1]
      // console.log('rule.field:',rule.field)
      // console.log(rule.field.split('.'))
      console.log('num',num)
      let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
      if (!value) {
        return callback(new Error("请输入"));
      } else if (regNumber.test(value) == false) {
        return callback(new Error("请填写大于0且最多保留两位小数的数值"));
      } else if (this.ruleForm.bpaccDataList[num].price <= value) {
        return callback(new Error("只能填写小于售价的数值"));
      }else {
        return callback();
      }
      
    };
    return {
      labelWidth: "150px",
      inputWidth: "420px",
      title: "新增首页弹窗活动",
      loading: false,
      disabled: false,
      AgreeLoading: false,
      ruleForm: {
        bpaData:{
          name: "", //活动名称
          img: "", //弹窗图片
          endTime: "", //活动结束时间
          startTime: "", //活动开始时间
          stock: '',//	活动名额
          joinCondition: '',//参与条件 1 不限 2 未消费过的用户
          rewardType: '',//积分类型 1 coco 2 椰分
          rewardNum: '',//领取数额
          cardId: [],//选择赚卡（校验用）
        },
        
        bpasData: {
          useNum: '',//抵用限制
        },
        bpaccDataList:[
          // {
          //   equityCardId: '',//赚卡ID
          //   deductionNum: '',//最高可用椰分抵扣
          // }
        ],

        date: [], //活动时间（校验用）
      },
      residueStock: 0,
      cardList: [],//赚卡列表
      xzAssetList: [],//奖励发放条件列表
      incentiveTypeList: [
        {id: '1',value: '积分'},
        {id: '2',value: '勋章'},
      ],
      integralTypeList: [
        // {id: '1',value: 'CoCo'},
        {id: '2',value: '椰分'},
      ],
      equityCardList: [],
      isSel: true,
      rules: {
        'bpaData.name': [
          { required: true,message: "请填写活动名称",trigger: ["change", "bulr"]}
        ],
        'bpaData.img': [
          {required: true, message: "请上传弹窗图片",trigger: ["change"]}
        ],
        date: [
          {required: true,message: "请选择活动时间",trigger: ["change"]}
        ],
        'bpaData.stock': [
          { validator: checkStock,required: true,trigger: ["change", "bulr"]}
        ],
        'bpaData.joinCondition': [
          { required: true,message: "请选择",trigger: ["change", "bulr"]}
        ],
        'bpaData.rewardType': [
          { required: true,message: "请选择",trigger: ["change", "bulr"]}
        ],
        'bpaData.rewardNum': [
          { validator: checkRewardNum,required: true,trigger: ["change", "bulr"]}
        ],

        'bpasData.useNum': [
          { validator: checkUseNum,required: true,trigger: ["change", "bulr"]}
        ],

        'bpaData.cardId': [
          { required: true,message: "请选择",trigger: ["change", "bulr"]}
        ],

        deductionNum: [
          { validator: checkDeductionNum,required: true,trigger: ["change", "bulr"]}
        ],

      },
      
    };
  },
  computed: {},
  created() {
    this.getcardSelect()
    console.log('this.pathType',this.pathType)
    if(this.pathType == 'edit'){
      this.title = '编辑首页弹窗活动'
      this.ruleForm.id = this.id
      this.getInfo()
    }
   
    // this.getCouponTypeList();
  },
  mounted() {
   
    
  },
  computed: {},
  methods: {
    //获取详情
    getInfo(){
      var id = this.ruleForm.id
      popActivityDetail(id).then(res => {
        this.ruleForm = {
          ...res.result,
          date: [],
        }
        this.ruleForm.bpaData.cardId = []
        console.log('this.ruleForm',this.ruleForm)
        this.residueStock = res.result.bpaData.stock - res.result.bpaData.soldStock
        this.ruleForm.bpaData.stock = 0
        // this.ruleForm.bpaccDataList.forEach(item => {
        //   this.ruleForm.bpaData.cardId.push(item)
        // })
        this.ruleForm.bpaData.cardId = this.ruleForm.bpaccDataList
        this.ruleForm.date[0] = res.result.bpaData.startTime
        this.ruleForm.date[1] = res.result.bpaData.endTime
        console.log('this.ruleForm1111111', this.ruleForm.bpaData.cardId)
      })
    },
   
    //获取店铺下拉
    getcardSelect(){
      cardSelect().then(res => {
        this.cardList = res.result
      })
    },
 
    //选择店铺
    changecardId(e){
      
      this.ruleForm.bpaccDataList = e
      this.ruleForm={...this.ruleForm}
      this.$forceUpdate();
    },
    //取消
    handleClose(formName) {
      this.$emit("update:visible", false);
    },
    successImg(e) {
      this.ruleForm.bpaData.img = e
      this.$refs['imgRef'].clearValidate();
    },
    // 删除图片
    handleRemove(){
      this.ruleForm.bpaData.img = ''
    },
    //删除店铺产品信息
    shopVOListdetele(e){
      this.ruleForm.bpaccDataList.splice(e,1)
      this.ruleForm.bpaData.cardId = this.ruleForm.bpaccDataList
      console.log('this.ruleForm.bpaData.cardId',this.ruleForm.bpaData.cardId)
    },
    removeTag(e,index){
      // var index = this.ruleForm.bpaData.cardId.length - 1
      // console.log('index',index)
      // this.ruleForm.bpaData.cardId.splice(index,1)
      // this.ruleForm.bpaccDataList.splice(index,1)
    },
    getTime(e){
      console.log("e",e)
      this.ruleForm.bpaData.startTime =  e[0] 
      this.ruleForm.bpaData.endTime = e[1]
      console.log("e",this.ruleForm.bpaData.startTime)
      console.log("e",this.ruleForm.bpaData.endTime)
    },
    
    submitForm(formName) {
      console.log(this.ruleForm);
      //创建确定
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.AgreeLoading = true
          
          var data = {
            ...this.ruleForm
          }
          if(this.pathType == 'add'){
            addPopActivity(data).then(res => {
              setTimeout(() => {
                this.handleClose()
                this.$message.success('创建成功')
                this.$emit('success')
                this.AgreeLoading = false
              }, 1000);
            }).finally(()=>{
              this.AgreeLoading = false
            })
          }else if(this.pathType == 'edit'){
            editPopActivity(data).then(res => {
              setTimeout(() => {
                this.handleClose()
                this.$message.success('修改成功')
                this.$emit('success')
                this.AgreeLoading = false
              }, 1000);
            }).finally(()=>{
              this.AgreeLoading = false
            })
          }
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    editForm(formName, status) {
      //编辑确定
      console.log(this.ruleForm);
      this.$refs[formName].validate(valid => {
        if (valid) {
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  }
};
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
    padding: 0 !important;
  }

  ::v-deep .ex--dialog--main {
    padding: 10px 20px !important;
  }
}
.el-select{
  width: 100%;
}
.main {
  padding: 20px 20px;
}
.title{
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
  padding: 10px 0;
  border-bottom: 4px solid #1890ff;
  margin-bottom: 20px;
}
.richText {
  border: 1px solid #ccc;
  line-height: normal;
}
.stockNum{
  display: flex;
  justify-content: center;
  padding-top: 10px;
}
.button_box{
  display: flex;
  justify-content: center;
}
.equityImgBox{
  width: 100%;
  display: flex;
  justify-content: center;
}
.equityImgBox img{
  width: 120px;
  height: 120px;
}
.el-form-item{
  margin-bottom: 32px;
}
.list_start{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .el-input{
    width: 300px;
    margin-left: 10px;
  }
}
</style>
